package com.company.app.services;

import javax.imageio.ImageIO;
import javax.swing.*;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

import com.company.app.constants.*;
import com.company.app.entities.*;
import com.company.app.utils.CommonKits;
import com.company.app.utils.ProcessTitle;

public class OpenPhotoHandler {
  public FrameValueObject openPhoto(FrameValueObject obj, String imagePath) {
    unfoldPhoto(obj.getBasePanel(), obj.getImageLabel(), imagePath);
    updateInterfaceTitle(obj, imagePath);

    System.out.println(this + " openPhoto:" + obj.getImageValObj().toString());
    return obj;
  }

  public void updateInterfaceTitle(FrameValueObject obj, String imagePath) {
    ProcessTitle p = new ProcessTitle();
    String title = p.getSingleTitle(imagePath);
    StringBuffer buffer = new StringBuffer();

    buffer.append("[");
    buffer.append(obj.getImageValObj().currentOrder + 1);
    buffer.append(" / ");
    buffer.append(obj.getImageValObj().currentPathsArray.length);
    buffer.append("] ");
    buffer.append(title);

    obj.getFrame().setTitle(buffer.toString());
  }

  public void unfoldPhoto(JPanel panel, JLabel imageLabel, String imagePath) {
    clearPanel(panel);
    JLabel label = new JLabel();
    File imageFile = new File(imagePath);// 获取当前索引位置的图片文件
    CommonKits kit = new CommonKits();

    String fileExtension = kit.getFileExtension(imagePath);
    System.out.println(this + "_unfoldPhoto_fileExtension=" + fileExtension);

    if (fileExtension.equals(FileExtension.WEBP_LOWER)) {
      WebpHandler webpHandler = new WebpHandler();
      label = webpHandler.showWebpImage(imageLabel, imagePath);

    } else if (fileExtension.equals(FileExtension.GIF_LOWER)) {
      LoadGifHandler load = new LoadGifHandler();
      label = load.showGifImage(imageLabel, imagePath, imageFile);

    } else if (fileExtension.equals(FileExtension.PNG_LOWER) || fileExtension.equals(FileExtension.JPEG_LOWER)
        || fileExtension.equals(FileExtension.JPG_LOWER)) {
      label = showImage(imageLabel, imagePath, imageFile);
    }

    panel.add(label, BorderLayout.CENTER);
  }

  public void clearPanel(JPanel panel) {
    // 移除 JPanel 中的所有子组件
    panel.removeAll();
    // 重新验证面板的布局
    panel.revalidate();
    // 重新绘制面板
    panel.repaint();
  }

  public JLabel showImage(JLabel imageLabel, String imagePath, File imageFile) {
    // 通过SwingWorker将图片加载和显示的逻辑放在单独的线程中来改善性能
    SwingWorker<BufferedImage, Void> worker = new SwingWorker<BufferedImage, Void>() {
      @Override
      protected BufferedImage doInBackground() throws Exception {// 先执行
        System.out.println(this + ".showImage.doInBackground.ThreadID=" + Thread.currentThread().getId());
        return ImageIO.read(imageFile); // 返回读取到的图片
      }

      @Override
      protected void done() {// 再执行
        try {
          BufferedImage img = get();
          if (img != null) {
            // 缩放旋转后的图片,并设置平滑缩放模式
            Image scaledImage = scaleImage(imageLabel, img);
            // 将缩放后的图片设置为 imageLabel 的图标
            imageLabel.setIcon(new ImageIcon(scaledImage));
          }
          System.out.println(this + ".showImage.done.ThreadID=" + Thread.currentThread().getId());
        } catch (Exception ex) {
          System.out.println(this + " Error loading image:" + ex.getMessage());
        }
      }
    };

    worker.execute();
    return imageLabel;
  }

  /**
   * 打开新图片之时,计算并设置初始化的图片尺寸
   * 
   * @param imageLabel
   * @param bufImg
   * @return
   */
  public Image scaleImage(JLabel imageLabel, BufferedImage bufImg) {
    // 获取图片的原始宽度和高度
    int originalWidth = bufImg.getWidth();
    int originalHeight = bufImg.getHeight();
    // 获取图片标签的宽度和高度
    int labelWidth = imageLabel.getWidth();
    int labelHeight = imageLabel.getHeight();
    // 计算宽度和高度的缩放比例
    double widthScale = (double) labelWidth / originalWidth;
    double heightScale = (double) labelHeight / originalHeight;
    double scale = Math.min(widthScale, heightScale);
    // 缩放图片,并设置平滑缩放模式
    return bufImg.getScaledInstance((int) (originalWidth * scale), (int) (originalHeight * scale), Image.SCALE_SMOOTH);
  }

}